package com.apes.scm.pur.purchaseOrder.model;

import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.BaseModel;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.util.ApesConst;
import com.apes.framework.util.Arith;
import com.apes.scm.account.tax.model.Tax;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.product.model.Product;
import com.apes.scm.masterdata.product.model.ProductUom;
import com.apes.scm.masterdata.product.service.UomService;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.Map;


/**
 * 功能：采购订单行
 *
 * @author xul
 * @create 2018-01-25 19:06
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = PurchaseOrderItem.CONST_TABLE_NAME)
public class PurchaseOrderItem extends BaseModel {
    public static final String CONST_TABLE_NAME = "pur_purchase_order_item";

    @Id
    @Column(name = "id")
    @ApesGenerator(code = CONST_TABLE_NAME, name = "采购订单行")
    @Comment("采购订单明细单号")
    private long id;

    @NotNull
    @ManyToOne(optional = false)
    @JoinColumn(name = "purchase_id", referencedColumnName = "id")
    @Comment("采购订单号")
    private PurchaseOrder purchaseOrder;

    @Transient
    private PartyRole owner; // 物权公司

    public PartyRole getOwner() {
        return this.purchaseOrder != null ? this.purchaseOrder.getLocation().getCompany() : null;
    }

    @Transient
    private PartyRole supplier; // 供应商

    public PartyRole getSupplier() {
        return this.purchaseOrder != null ? this.purchaseOrder.getSupplier() : null;
    }

    @Column(name = "name", length = 120)
    @Comment("说明")
    private String name;

    @Column(name = "price_subtotal", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("未含税金额")
    private double priceSubtotal = 0;

    @Column(name = "price_tax", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("税金")
    private double priceTax = 0;

    @Column(name = "price_total", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("总计")
    private double priceTotal = 0;

    @Column(name = "price_unit", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("单价")
    private double priceUnit = 0;

    public void judgePriceUnit() {
        if (Arith.compare(priceUnit, 0, 8) != 1) {
            throw new RuntimeException("单价不能为0和负数！");
        }
    }

    @Column(name = "price_ceiling", nullable = false, columnDefinition = ApesConst.FIELD_16_4_0)
    @Comment("最高限价")
    private double priceCeiling = 0;

    @Column(name = "product_uom_qty", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("订货数量")
    private double productUomQty = 0;

    @Column(name = "stop_qty", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("终止数量")
    private double stopQty = 0;

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "product_uom_id", referencedColumnName = "id")
    @Comment("计量单位编码")
    private ProductUom uom;

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "tax_id", referencedColumnName = "id")
    @Comment("税率编码")
    private Tax tax;

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "product_id", referencedColumnName = "id")
    @Comment("商品编码")
    private Product product;

    @Column(name = "qty_invoiced", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("开票数量")
    private double qtyInvoiced = 0;

    @Column(name = "qty_received", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("已收货数量")
    private double qtyReceived = 0;

    @Column(name = "effective_qty", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("有效数量")
    private double effectiveQty; // 激活终止时使用, 默认跟订货数量一致

    @Column(name = "solicitation_qty", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("揽件数量")
    private double solicitationQty;

    @Column(name = "demandQty", columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("要货数量")
    private double demandQty = 0; // 老切新, 订货数量会以供应商的数量为准, 这个为最初始的数量

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "source_state", referencedColumnName = "id" )
    @Comment("货源状态")
    private Enumeration sourceState;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "settlement_type", referencedColumnName = "id")
    @Comment("结算方式（month：月结，halfMonth：半月结，week：周结，bill：账单，totalCash：总部现金，deptCash：门店现金）")
    private Enumeration settlementType;

    @Column(name = "expected_arrival_time", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("预计到货时长")
    private double expectedArrivalTime = 0;

    @Column (name ="note")
    @Comment("备注")
    private String note;

    @Column (name ="external_code")
    @Comment("外部编码")
    private String externalCode;

    @Column (name ="source_item_id")
    @Comment("上游单据明细编码")
    private String sourceItemId;

    /*
     * 实际数量
     */
    public double computeProductQty() {
        return computeQtyUnit(productUomQty);
    }


    public void computeAmt() {
        Map result = this.getTax().computeAll(this.getPurchaseOrder().getCompany(), priceUnit, productUomQty);
        priceTax = ((Double) result.get("taxAmt")).doubleValue();
        priceSubtotal = ((Double) result.get("totalExcluded")).doubleValue();
        priceTotal = ((Double) result.get("totalIncluded")).doubleValue();
    }

    /*
     * 功能：计算基本单位含税库存单价
     */
    public double computePriceUnit() {
        double price = this.priceUnit;
        ProductUom baseUom = getProductUom();
        if (this.getUom().getId() != baseUom.getId()) {
            price = this.getUom().computePrice(price, baseUom);
        }
        return price;
    }

    /*
     * 功能：计算基本单位库存量
     */
    public double computeQtyUnit(double uomQty) {
        ProductUom baseUom = getProductUom();
        if (this.getUom().getId() != baseUom.getId()) {
            return this.getUom().computeQty(uomQty, baseUom, true);
        }
        return uomQty;
    }

    private ProductUom getProductUom() {
        UomService uomService = SpringManager.getBean(UomService.class);
        return uomService.getUom(this.getPurchaseOrder().getCompany(), this.getProduct());
    }

    /**
     * 交货
     */
    public void delivery(double qtyDone) {
        this.qtyReceived += qtyDone;
        if (qtyReceived > productUomQty) {
            throw new RuntimeException("接收数量不允许大于订单数量！");
        }
    }


}
